package com.example.words;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;

import com.google.android.material.snackbar.Snackbar;

import java.util.List;


public class WordsFragment extends Fragment {

    private WordViewModel wordViewModel;
    private RecyclerView recyclerView;
    private MyAdapter myAdapter1,myAdapter2;
    private LiveData<List<Word>> filteredWords;
    private List<Word> allWords;
    private DividerItemDecoration dividerItemDecoration;

    public WordsFragment() {
        // Required empty public constructor
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_words, container, false);
    }

    @Override
    public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        wordViewModel= ViewModelProviders.of(requireActivity()).get(WordViewModel.class);
        recyclerView=requireActivity().findViewById(R.id.recycleView);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));
        myAdapter1=new MyAdapter(false,wordViewModel);
        myAdapter2=new MyAdapter(true,wordViewModel);

        //重新刷新可见视图的序号
        recyclerView.setItemAnimator(new DefaultItemAnimator(){
            @Override
            public void onAnimationFinished(@NonNull RecyclerView.ViewHolder viewHolder) {
                super.onAnimationFinished(viewHolder);
                LinearLayoutManager linearLayoutManager= (LinearLayoutManager) recyclerView.getLayoutManager();
                if (linearLayoutManager!=null){
                    int fistPosition = linearLayoutManager.findFirstCompletelyVisibleItemPosition();
                    int lastPosition = linearLayoutManager.findLastCompletelyVisibleItemPosition();
                    for (int i=fistPosition;i<=lastPosition;i++){
                        MyAdapter.MyViewHolder holder= (MyAdapter.MyViewHolder) recyclerView.findViewHolderForAdapterPosition(i);
                        if (holder!=null){
                            holder.textViewNumber.setText(String.valueOf(i+1));
                        }
                    }
                }
            }
        });

        dividerItemDecoration=new DividerItemDecoration(requireActivity(),DividerItemDecoration.VERTICAL);
        SharedPreferences shp=requireActivity().getSharedPreferences("view_type_shp",Context.MODE_PRIVATE);
        if (shp.getBoolean("is_use_card_view", false)){
            recyclerView.setAdapter(myAdapter2);
        }else{
            recyclerView.addItemDecoration(dividerItemDecoration);
            recyclerView.setAdapter(myAdapter1);
        }

        filteredWords=wordViewModel.getAllWordsLive();
        filteredWords.observe(getViewLifecycleOwner(), new Observer<List<Word>>() {
            @Override
            public void onChanged(List<Word> words) {
                int temp=myAdapter1.getItemCount();
                allWords=words;
                if (temp!=words.size()){
                    //myAdapter1.notifyDataSetChanged();//通知adapter在页面数据改变时刷新
                    //myAdapter2.notifyDataSetChanged();//通知adapter在页面数据改变时刷新
                    recyclerView.smoothScrollBy(0,-200); //使视图平滑滚动200像素
                    myAdapter1.submitList(words);
                    myAdapter2.submitList(words);
                }
            }
        });

        //滑动删除
        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.START | ItemTouchHelper.END) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                final Word wordToDelete = allWords.get(viewHolder.getAdapterPosition());
                wordViewModel.deleteWords(wordToDelete);
                Snackbar.make(requireActivity().findViewById(R.id.wordsFrameView),"删除了一个词汇",Snackbar.LENGTH_SHORT)
                        .setAction("撤销", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                wordViewModel.insertWords(wordToDelete);
                            }
                        }).show();
            }
            Drawable icon= ContextCompat.getDrawable(requireContext(),R.drawable.ic_baseline_delete_forever_24);
            Drawable background=new ColorDrawable(Color.LTGRAY);
            @Override
            public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
                View itemView=viewHolder.itemView;
                int iconMargin=(itemView.getHeight()-icon.getIntrinsicHeight())/2;
                int iconLeft,iconRight,iconTop,iconBottom;
                int backTop,backBottom,backLeft,backRight;
                backTop=itemView.getTop();
                backBottom=itemView.getBottom();
                iconTop=itemView.getTop() + (itemView.getHeight()-icon.getIntrinsicHeight()) /2;
                iconBottom=iconTop+icon.getIntrinsicHeight();
                if(dX>0){
                    backLeft=itemView.getLeft();
                    backRight=itemView.getLeft()+(int)dX;
                    background.setBounds(backLeft,backTop,backRight,backBottom);
                    iconLeft=itemView.getLeft()+iconMargin;
                    iconRight=iconLeft+icon.getIntrinsicWidth();
                    icon.setBounds(iconLeft,iconTop,iconRight,iconBottom);
                }else if(dX<0){
                    backRight=itemView.getRight();
                    backLeft=itemView.getRight()+(int)dX;
                    background.setBounds(backLeft,backTop,backRight,backBottom);
                    iconRight=itemView.getRight()-iconMargin;
                    iconLeft=iconRight-icon.getIntrinsicWidth();
                    icon.setBounds(iconLeft,iconTop,iconRight,iconBottom);
                }else{
                    background.setBounds(0,0,0,0);
                    icon.setBounds(0,0,0,0);
                }
                background.draw(c);
                icon.draw(c);
            }
        }).attachToRecyclerView(recyclerView);

        requireActivity().findViewById(R.id.floatingActionButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NavController controller= Navigation.findNavController(view);
                controller.navigate(R.id.action_wordsFragment_to_addFragment);
            }
        });
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.main_menu,menu);
        SearchView searchView= (SearchView) menu.findItem(R.id.app_bar_search).getActionView();
        searchView.setMaxWidth(700);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                filteredWords.removeObservers(getViewLifecycleOwner());
                filteredWords = wordViewModel.findWordsWithPattern(s.trim());
                filteredWords.observe(getViewLifecycleOwner(), new Observer<List<Word>>() {
                    @Override
                    public void onChanged(List<Word> words) {
                        int temp=myAdapter1.getItemCount();
                        allWords=words;
                        if (temp!=words.size()){
                            //myAdapter1.notifyDataSetChanged();//通知adapter在页面数据改变时刷新
                            //myAdapter2.notifyDataSetChanged();//通知adapter在页面数据改变时刷新
                            myAdapter1.submitList(words);
                            myAdapter2.submitList(words);
                        }
                    }
                });
                return true;
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.clearData:
                AlertDialog.Builder builder=new AlertDialog.Builder(requireActivity());
                builder.setTitle("清空数据");
                builder.setPositiveButton("确定！", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        wordViewModel.ClearWords();
                    }
                });
                builder.setNegativeButton("取消！", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
                builder.create();
                builder.show();
                break;
            case R.id.switchView:
                SharedPreferences shp=requireActivity().getSharedPreferences("view_type_shp",Context.MODE_PRIVATE);
                SharedPreferences.Editor editor=shp.edit();
                boolean b = shp.getBoolean("is_use_card_view", false);
                if (b){
                    recyclerView.addItemDecoration(dividerItemDecoration);
                    recyclerView.setAdapter(myAdapter1);
                    editor.putBoolean("is_use_card_view",false);
                }else{
                    recyclerView.removeItemDecoration(dividerItemDecoration);
                    recyclerView.setAdapter(myAdapter2);
                    editor.putBoolean("is_use_card_view",true);
                }
                editor.apply();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}